<template>
	<div class="login-page full box relative">
		<view class="wx-login-box">
			<view class="login-tip">
				<text>小程序需要登录注册才能使用相关功能，申请获取以下权限</text>
			</view>
			<view class="login-tip">
				<text>获得你的公开信息(昵称、头像、手机号码等)</text>
			</view>
			<view class="login-btn">
				<u-button open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber" shape="circle"
					type="primary">授权登录</u-button>
				<u-button class="no-auth-btn" shape="circle" type="primary" plain>暂不授权</u-button>
			</view>
		</view>
		<!-- <div class="login-title">
			<span>账号密码登录</span>
		</div>
		<div class="login-form">
			<div class="form-item">
				<span class="form-label">手机号</span>
				<input class="form-input" v-model="userPhone" type="text" placeholder="请输入手机号" />
			</div>
			<div class="form-item active">
				<span class="form-label">密码</span>
				<input v-if="showPassword" v-model="password" type="text" placeholder="请输入密码" class="form-input" />
				<input v-else v-model="password" type="password" placeholder="请输入密码" class="form-input" />
				<u-icon @click="handleToggleShowPassword" size="40rpx" color="#999999"
					:name="showPassword ? 'eye' : 'eye-off'" />
			</div>
			<div class="button-box">
				<u-button :loading="loading" type="primary" @click="handleLogin">立即登录</u-button>
			</div>
			<div class="service-box">
				<div @click="handleToggleCheck" class="checkbox-wrap" :class="[isCheck ? 'active' : '']">
					<u-icon v-if="isCheck" name="checkmark" color="#fff" size="30rpx" />
				</div>
				<span class="red-text" @click="handleToggleCheck">我已阅读并同意</span>
				<span class="service-text" @click="handleToService">《用户服务协议》</span>
			</div>
		</div> -->
	</div>
</template>

<script>
	import { toast, request, showLoading, delay } from '@/utils/tool.js'
	import { account, mnpLogin } from '@/utils/login.js'
	import { isDev } from "@/utils/env.js"
	export default {
		data() {
			return {
				userPhone: isDev ? "zsl15757115639" : "",
				password: isDev ? "z,s,l,123456" : "",
				showPassword: false,
				isCheck: false,
				loading: false,
				//判断是否勾选
				value: '',
				tel: '',
				pwd: ''
			}
		},
		methods: {
			async handleGetPhoneNumber(ev) {
				const { code } = ev.detail
				uni.login({
					provider: "weixin",
					success: async loginEv => {
						const hide = showLoading("正在登录")
						const { code: loginCode } = loginEv
						const [openIdErr, openIdResp] = await this.getOpenId(loginCode).catch(hide)
						if (openIdErr) {
							hide()
							return toast({ title: "获取openid失败" })
						}
						const { openid } = openIdResp
						const resp = await request({
							url: '/login/mnpmobileLogin',
							data: {
								openid,
								code
							}
						}).catch(hide)
						if (resp.code !== 1) {
							toast({ title: resp.msg || "登录失败" })
							return hide()
						}
						toast({ title: "登录成功", icon: "success" })
						const data = resp.data
						uni.setStorageSync('token', data.token)
						await this.$store.dispatch("initUserDevice")
						uni.showMsg('登录成功', 'success').then(() => {
							this.loading = false
							hide()
							uni.reLaunch({
								url: '/pages/index/index'
							})
						})
					},
					fail: error => {

					}
				})
			},
			async getOpenId(code) {
				return new Promise(async resolve => {
					const resp = await request({
						url: '/login/mnpGetOpenid',
						data: {
							code
						}
					})
					if (resp.code !== 1) {
						return resolve([resp.data, null])
					}
					resolve([null, resp.data])
				})
			},
			handleWxLogin() {
				uni.login({
					provider: "weixin",
					success: async ev => {
						const hide = showLoading("正在登录")
						const { code } = ev
						const resp = await request({
							url: "/login/mnpLogin",
							data: {
								code
							}
						}).catch(hide)
						if (resp.code !== 1) {
							toast({ title: resp.msg || "登录失败", icon: "error" })
							return hide()
						}
						toast({ title: "登录成功", icon: "success" })
						const data = resp.data
						uni.setStorageSync('token', data.token)
						await this.$store.dispatch("initUserDevice")
						uni.showMsg('登录成功', 'success').then(() => {
							this.loading = false
							hide()
							uni.reLaunch({
								url: '/pages/index/index'
							})
						})
					},
					fail: error => {
						toast({ title: "获取code失败", icon: "error" })
					}
				})
			},
			async handleLogin() {
				const { userPhone, password, isCheck } = this
				if (!userPhone) return toast({ title: "请输入手机号" })
				if (!password) return toast({ title: "请输入密码" })
				if (!isCheck) return toast({ title: "请勾选用户协议" })
				const hide = showLoading("正在登录")
				this.loading = true
				const resp = await request({
					url: "/login/account",
					data: {
						account: userPhone,
						terminal: 1,
						scene: 1,
						password
					}
				}).catch(() => {
					hide()
					this.loading = false
				})
				hide()
				console.log(resp, 'resp');
				const { code, msg, data } = resp
				if (code !== 1) {
					this.loading = false
					if (msg) toast({ title: msg, icon: "error" })
					return
				}
				uni.setStorageSync('token', data.token)
				await this.$store.dispatch("initUserDevice")
				uni.showMsg('登录成功', 'success').then(() => {
					this.loading = false
					uni.reLaunch({
						url: '/pages/index/index'
					})
				})
			},
			handleToService() {
				uni.navigateTo({
					url: "/pages/mine/service?type=service"
				})
			},
			handleToggleCheck() {
				this.isCheck = !this.isCheck
			},
			handleToggleShowPassword() {
				this.showPassword = !this.showPassword
			},
			// 协议勾选
			handleChange(e) {
				this.value = e.detail.value;
			},
			// 协议
			handleXI(cent) {
				uni.navigateTo({
					url: '/pages/userAgreement?text=' + cent
				})
			},
			// 暂不登录
			btnWxNo() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			// 微信小程序登录
			bntWxLogin() {
				if (this.value.length == 0) return uni.showMsg('请先阅读并勾选《用户服务协议》和《隐私政策》')
				uni.showLoading({
					title: '登录中...',
					mask: true
				})
				uni.login({
					provider: 'weixin', //使用微信登录
					success: (loginRes) => {
						if (loginRes.errMsg == "login:ok") {
							mnpLogin({
								code: loginRes.code, //账号
							}).then((res) => {
								if (res.code == 1) {
									uni.setStorageSync('token', res.data.token)
									uni.showMsg('登录成功', 'success').then(() => {
										uni.reLaunch({
											url: '/pages/index/index'
										})
									})
								} else {
									uni.showMsg(res.msg)
								}
							}).catch((err) => {
								uni.hideLoading()
							})
						} else {
							uni.hideLoading()
						}
					}
				})
			},
			// 立即登录
			btnLogin() {
				if (!this.tel) return uni.showMsg('请输入账号！')
				if (!this.pwd) return uni.showMsg('请输入密码！')
				if (this.value.length == 0) return uni.showMsg('请先阅读并勾选《用户服务协议》和《隐私政策》')
				account({
					account: this.tel, //账号
					terminal: 1, //客户端类型：1-微信小程序；2-微信公众号；3-手机H5；4-电脑PC；5-苹果APP；6-安卓APP
					scene: 1, //登录场景 1-账号/手机号登录 2-手机号验证码登录
					password: this.pwd, //密码 - 账号密码场景时必填
					code: '' //验证码-手机验证码登录时必填
				}).then(res => {
					if (res.code == 1) {
						getApp().globalData.isType = res.data.type;
						uni.setStorageSync('token', res.data.token);
						var baseURL = res.data.type == 1 ? '/pages/index/index' : '/pages/order/index'
						uni.showMsg('登录成功', 'success').then(() => {
							setTimeout(() => {
								uni.reLaunch({
									url: baseURL
								})
							}, 1000)
						})
					} else if (res.code == 0) {
						uni.showMsg(res.msg)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-page {
		.wx-login-box {
			padding: 300rpx 64rpx;

			.login-btn {
				display: flex;
				flex-flow: column;
				padding-top: 32rpx;

				.no-auth-btn {
					margin-top: 32rpx;
				}
			}

			.login-tip {
				font-size: 28rpx;
				color: #86909C;
				line-height: 48rpx;
				text-align: center;
			}
		}

		.service-box {
			display: flex;
			justify-content: center;
			align-items: center;

			.red-text {
				height: 48rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #888888;
				line-height: 48rpx;
				padding: 0 10rpx;
			}

			.service-text {
				height: 48rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #3361F0;
				line-height: 48rpx;
			}

			.checkbox-wrap {
				width: 40rpx;
				height: 40rpx;
				border: 2rpx solid #3361F0;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				transition: all .2s;

				&.active {
					background: #3361F0;
				}
			}
		}

		.login-form {
			padding: 0 32rpx;
			box-sizing: border-box;

			.button-box {
				padding: 88rpx 32rpx 24rpx;
				box-sizing: border-box;

				uni-button {
					border-radius: 80rpx 80rpx 80rpx 80rpx;
				}
			}

			.form-item {
				display: flex;
				align-items: center;
				box-sizing: border-box;
				padding: 32rpx;
				border-bottom: 2rpx solid #f1f1f1;

				&.active {
					border-bottom: 0;
				}

				.form-label {
					width: 162rpx;
					font-weight: 400;
					font-size: 32rpx;
					color: rgba(0, 0, 0, 0.9);
					line-height: 48rpx;
				}

				.form-input {
					flex: 1;
					height: 48rpx;
					font-weight: 400;
					font-size: 32rpx;
					color: rgba(0, 0, 0, 0.9);
					line-height: 48rpx;
				}
			}
		}

		.login-title {
			padding: 238rpx 64rpx 192rpx;
			box-sizing: border-box;
			position: relative;
			font-weight: 600;
			font-size: 48rpx;
			color: rgba(0, 0, 0, 0.9);
			line-height: 64rpx;
		}
	}
</style>